package com.motong.gongdan.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.entity.*;
import com.motong.gongdan.enums.ObjectType;
import com.motong.gongdan.service.*;
import com.motong.gongdan.util.*;
import com.motong.gongdan.vo.system.CustomField.*;
import com.motong.gongdan.vo.system.otherVo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author:fff
 * @time:2022/4/12
 */
@Api(value = "自定义字段", tags = {"自定义字段"})
@RestController
@RequestMapping(value = "/sys/custom_field/")
public class CustomFieldController {
    @Resource
    CustomFieldService customFieldService;
    @Resource
    UserService userService;
    @Resource
    CustomNumberService customNumberService;
    @Resource
    UnitService unitService;
    @Resource
    BadProductService badProductService;
    @Resource
    ProcessesService processesService;
    @Resource
    ProcessRouteService processRouteService;
    @Resource
    ProductService productService;
    @Resource
    WorkOrderService workOrderService;
    @Resource
    WorkReportService workReportService;
    @Resource
    StockDetailService stockDetailService;
    @Resource
    StockMsgService stockMsgService;
    @Resource
    FormCheckRuleService formCheckRuleService;
    @Resource
    MatchingRuleService matchingRuleService;


    @UserLoginToken
    @ApiOperation(value = "自定义字段for页面create")
    @RequestMapping(value = "custom_field_other", method = RequestMethod.GET)
    public ResponseData customFieldOther(String type) {
        List<CustomFieldVo> resultList = new ArrayList<>();
        List<CustomField> list = customFieldService.list(new QueryWrapper<CustomField>().eq("field_ascription", type).orderByDesc("sort"));
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(l -> {
                User u = userService.getById(l.getCreateId());
                CustomFieldVo vo = new CustomFieldVo();
                if ("relevanceObject".equals(l.getFieldType()) && StringUtil.isNotBlank(l.getBusinessObject())) {
                    switch (l.getBusinessObject()) {
                        case "unit":
                            List<Unit> units = unitService.list();
                            vo.setObjectsValue(units);
                            break;
                        case "badProduct":
                            List<BadProduct> badProductList = badProductService.list();
                            vo.setObjectsValue(badProductList);
                            break;
                        case "product":
                            List<Product> products = productService.list(new QueryWrapper<Product>().eq("del_flag", 0));
                            vo.setObjectsValue(products);
                            break;
                        case "processes":
                            List<Processes> processes = processesService.list();
                            vo.setObjectsValue(processes);
                            break;
                        case "processRoute":
                            List<ProcessRoute> processRoutes = processRouteService.list();
                            vo.setObjectsValue(processRoutes);
                            break;
                        case "user":
                            List<User> userList = userService.list(new QueryWrapper<User>().eq("factory_id", LoginUtil.getLoginUserFactory()).eq("state", 0));
                            vo.setObjectsValue(userList);
                            break;
                    }
                }
                if (StringUtils.hasLength(l.getFieldAttribute()) && "inputNumber".equals(l.getFieldType())) {
                    l.setIsRequired(l.getFieldAttribute().contains("required") ? 1 : 0);
                }
                l.setCreateName(u.getName());
                vo.setCustomFieldMess(l);
                vo.setCustomFieldId(l.getId());
                vo.setName(l.getChineseName());
                resultList.add(vo);
            });
        }
        return ResponseData.success(resultList);
    }

    @UserLoginToken
    @ApiOperation(value = "自定义字段列表")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ResponseData list(@RequestBody NormalVo vo) {
        IPage<CustomField> data = customFieldService.page(new Page<>(vo.getPage(), vo.getLimit()),
                new QueryWrapper<CustomField>().eq("field_ascription", vo.getName()).orderByDesc("sort", "id"));
        if (!CollectionUtils.isEmpty(data.getRecords())) {
            data.getRecords().stream().forEach(d -> {
                if (d.getCreateId() != null) {
                    User u = userService.getById(d.getCreateId());
                    d.setCreateName(u.getName());
                }
            });
        }
        return ResponseData.success(data);
    }

    @UserLoginToken
    @ApiOperation(value = "自定义字段操作")
    @RequestMapping(value = "handle", method = RequestMethod.POST)
    public ResponseData handle(@RequestBody CustomField vo) {
        if (vo.getId() == null) {
            CustomField cf = customFieldService.getOne(new QueryWrapper<CustomField>().eq("chinese_name", vo.getChineseName()).eq("field_ascription", vo.getFieldAscription()));
            Map<String, String> cnEnData = ColumnUtils.BASE_COLUMN_CN_EN_MAP.getOrDefault(vo.getFieldAscription(), Collections.emptyMap());
            if (cf != null || Objects.nonNull(cnEnData.get(vo.getChineseName()))) {
                return ResponseData.fail(500, "字段名称已存在");
            }
            vo.setCreateId(LoginUtil.getLoginUserId());
            vo.setCreateTime(new Date());
            vo.setUpdateTime(new Date());
        }
        customFieldService.saveOrUpdate(vo);
        if (vo.getSort() == null) {
            vo.setSort(vo.getId());
            customFieldService.saveOrUpdate(vo);
        }
        return ResponseData.success("success");
    }

    @UserLoginToken
    @ApiOperation(value = "自定义字段删除")
    @RequestMapping(value = "del", method = RequestMethod.POST)
    public ResponseData del(@RequestBody IdVo vo) {
        CustomField cf = customFieldService.getById(vo.getId());
        if (cf != null) {
            List<CustomFieldVo> vos = new ArrayList<>();
            switch (cf.getFieldAscription()) {
                case "product":
                    List<Product> list = productService.list(new QueryWrapper<Product>().isNotNull("other").ne("other", ""));
                    long relevanceObjectCount = customFieldService.count(new LambdaQueryWrapper<CustomField>().eq(CustomField::getFieldType, "relevanceObject")
                            .and(i -> i.like(CustomField::getFillRule, ":" + cf.getId() + ",").or().like(CustomField::getFillRule, ":" + cf.getId() + "}")));
                    if (relevanceObjectCount > 0) {
                        return ResponseData.fail(500, "使用中无法删除");
                    }
                    if (!CollectionUtils.isEmpty(list)) {
                        list.forEach(l -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(l.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            list.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    productService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
                case "user":
                    List<User> userList = userService.list(new QueryWrapper<User>().isNotNull("other").ne("other", ""));
                    if (!CollectionUtils.isEmpty(userList)) {
                        userList.forEach(u -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(u.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            userList.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    userService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
                case "processes":
                    List<Processes> processes = processesService.list(new QueryWrapper<Processes>().isNotNull("other").ne("other", ""));
                    if (!CollectionUtils.isEmpty(processes)) {
                        processes.forEach(u -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(u.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            processes.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    processesService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
                case "workOrder":
                    List<WorkOrder> workOrderList = workOrderService.list(new QueryWrapper<WorkOrder>().isNotNull("other").ne("other", ""));
                    if (!CollectionUtils.isEmpty(workOrderList)) {
                        workOrderList.forEach(u -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(u.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            workOrderList.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    workOrderService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
                case "workReport":
                    List<WorkReport> workReports = workReportService.list(new QueryWrapper<WorkReport>().isNotNull("other").ne("other", ""));
                    if (!CollectionUtils.isEmpty(workReports)) {
                        workReports.forEach(u -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(u.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            workReports.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    workReportService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
                case "stockMsg":
                    List<StockDetail> stockDetails = stockDetailService.list(new QueryWrapper<StockDetail>().isNotNull("other").ne("other", ""));
                    if (!CollectionUtils.isEmpty(stockDetails)) {
                        stockDetails.forEach(u -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(u.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            stockDetails.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    stockDetailService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
                case "stock":
                    List<StockMsg> stockMsgs = stockMsgService.list(new QueryWrapper<StockMsg>().isNotNull("other").ne("other", ""));
                    if (!CollectionUtils.isEmpty(stockMsgs)) {
                        stockMsgs.forEach(u -> {
                            vos.addAll(customFieldService.handleCustomFieldForList(u.getOther()));
                        });
                        if (inuse(vos, vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else if (mapRuleInUse(vo.getId())) {
                            return ResponseData.fail(500, "使用中无法删除");
                        } else {
                            customFieldService.removeById(cf.getId());
                            stockMsgs.forEach(l -> {
                                if (StringUtil.isNotBlank(handleDelField(l.getOther(), vo.getId()))) {
                                    l.setOther(handleDelField(l.getOther(), vo.getId()));
                                    stockMsgService.updateById(l);
                                }
                            });
                        }
                    } else {
                        customFieldService.removeById(cf.getId());
                    }
            }
//            List<ColumnsConfigure> list = new ArrayList<>();
//            if(cf.getFieldAscription().equals("stock")){
//                list = customFieldService.handleDefaultColumns("stockIn",false);
//                RedisUtil.set(cf.getFieldAscription()+"_columns:0",JSONArray.parseArray(JSON.toJSONString(list)));
//                List<ColumnsConfigure> list1 = customFieldService.handleDefaultColumns("stockOut",false);
//                RedisUtil.set(cf.getFieldAscription()+"_columns:0",JSONArray.parseArray(JSON.toJSONString(list1)));
//            }else{
//                list = customFieldService.handleDefaultColumns(cf.getFieldAscription(),false);
//                RedisUtil.set(cf.getFieldAscription()+"_columns:0",JSONArray.parseArray(JSON.toJSONString(list)));
//                RedisUtil.set("productForm"+"_columns:0",JSONArray.parseArray(JSON.toJSONString(list)));
//            }
            return ResponseData.success("success");
        }
        return null;
    }

    public String handleDelField(String other, Integer id) {
        if (StringUtil.isNotBlank(other) && !other.equals("[]")) {
            List<CustomFieldVo> customFieldVos = customFieldService.handleCustomFieldForList(other);
            boolean exist = customFieldVos.stream().filter(f -> f.getCustomFieldId() == id).findAny().isPresent();
            if (exist) {
                List<CustomFieldVo> newCustomFieldVos = customFieldVos.stream().filter(f -> f.getCustomFieldId() != id).collect(Collectors.toList());
                return customFieldService.handleObjectCreateOrEdit(newCustomFieldVos).toJSONString();
            } else {
                return other;
            }
        }
        return null;
    }

    public boolean inuse(List<CustomFieldVo> list, Integer id) {
        boolean exist = list.stream().filter(f -> f.getCustomFieldId().equals(id)).findAny().isPresent();
        return exist;
    }

    public boolean mapRuleInUse(Integer id) {
        MatchingRule matchingRule = matchingRuleService.getOne(new QueryWrapper<MatchingRule>().eq("cus_field", id).eq("state", 1));
        if (matchingRule != null) {
            return true;
        } else {
            return false;
        }

    }

    @UserLoginToken
    @ApiOperation(value = "自定义编号规则")
    @RequestMapping(value = "custom_num", method = RequestMethod.POST)
    public ResponseData customNum(@RequestBody PageVo vo) {
        IPage<CustomNumber> data = customNumberService.page(new Page(vo.getPage(), vo.getLimit()));
        return ResponseData.success(data);
    }

    @UserLoginToken
    @ApiOperation(value = "自定义编号规则修改")
    @RequestMapping(value = "custom_num_handle", method = RequestMethod.POST)
    public ResponseData customNumHandle(@RequestBody CustomNumber vo) {
        vo.setNowNum(0);
        customNumberService.updateById(vo);
        return ResponseData.success("success");
    }


    @UserLoginToken
    @ApiOperation(value = "关联业务对象字段列表")
    @RequestMapping(value = "object_field", method = RequestMethod.POST)
    public ResponseData objectField() {
        String str = OwnUtil.readFileTxt("objectField.txt");
        JSONArray jsonArray = JSON.parseArray(str);
        List<ObjectField> list = jsonArray.toJavaList(ObjectField.class);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(l -> {
                List<CustomField> customFields = customFieldService.list(new QueryWrapper<CustomField>().eq("field_ascription", l.getBusinessObjectCode()));
                if (!CollectionUtils.isEmpty(customFields)) {
                    customFields.forEach(c -> {
                        ObjectFieldDown ofd = new ObjectFieldDown();
                        ofd.setAttributeCode(c.getName());
                        ofd.setAttributeName(c.getChineseName());
                        ofd.setAttributeType(1);
                        ofd.setAttributeTypeName(c.getFieldType());
                        ofd.setAttributePath(c.getName());
                        ofd.setAttributeOther("${" + ObjectType.getDescByCode(c.getFieldAscription()) + "." + c.getChineseName() + "}");
                        l.getAttributes().add(ofd);
                    });
                }
            });
        }
        return ResponseData.success(list);
    }

    @UserLoginToken
    @ApiOperation(value = "自定义字段详情")
    @RequestMapping(value = "field_mess", method = RequestMethod.POST)
    public ResponseData fieldMess(@RequestBody IdVo vo) {
        CustomField cf = customFieldService.getById(vo.getId());
        User u = userService.getById(cf.getCreateId());
        cf.setCreateName(u.getName());
        return ResponseData.success(cf);
    }

    @UserLoginToken
    @ApiOperation(value = "表头列配置操作")
    @RequestMapping(value = "product_columns", method = RequestMethod.POST)
    public ResponseData productColumns(@RequestBody ColumnsHandle vo) throws Exception {

        if (vo.getType().equals("wages")) {
            if (!CollectionUtils.isEmpty(vo.getConfigureList())) {
                JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(vo.getConfigureList()));
                RedisUtil.set(vo.getType() + "_columns:" + LoginUtil.getLoginUserId(), jsonArray);
            }
            List<ColumnsConfigure> configureList;
            configureList = customFieldService.wagesRedisHandle();
            configureList.forEach(i -> {
                if ("createUser".equals(i.getName())) {
                    i.setName("createName");
                }
            });
            List<ColumnsConfigure> finalConfigureList = configureList;
            if (!CollectionUtils.isEmpty(finalConfigureList)) {
                JSONArray userJsonArray = (JSONArray) RedisUtil.get(vo.getType() + "_columns:" + LoginUtil.getLoginUserId());
                if (userJsonArray != null && !userJsonArray.isEmpty()) {
                    List<ColumnsConfigure> userColumns = userJsonArray.toJavaList(ColumnsConfigure.class);
                    if (!CollectionUtils.isEmpty(userColumns)) {
                        List<ColumnsConfigure> existColumns = new ArrayList<>();
                        List<ColumnsConfigure> finalConfigureList1 = finalConfigureList;
                        userColumns.forEach(i -> {
                            ColumnsConfigure cc = finalConfigureList1.stream().filter(f -> f.getName().equals(i.getName())).findAny().orElse(null);
                            if (Objects.nonNull(cc)) {
                                existColumns.add(i);
                            }
                        });
                        List<ColumnsConfigure> otherColumns = finalConfigureList.stream().filter(i -> !existColumns.stream().map(ColumnsConfigure::getName).collect(Collectors.toList()).contains(i.getName())).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(otherColumns)){
                            existColumns.addAll(otherColumns);
                        }
                        finalConfigureList = existColumns;
                    }
                }

            }
            RedisUtil.set(vo.getType() + "_columns:" + LoginUtil.getLoginUserId(), JSONArray.parseArray(JSON.toJSONString(finalConfigureList)));
            return ResponseData.success(finalConfigureList);
        } else {
            if (!CollectionUtils.isEmpty(vo.getConfigureList())) {
                JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(vo.getConfigureList()));
                RedisUtil.set(vo.getType() + "_columns:" + LoginUtil.getLoginUserId(), jsonArray);
            }
            List<ColumnsConfigure> defaultColumns = customFieldService.handleDefaultColumns(vo.getType(), false);
            defaultColumns.forEach(i -> {
                if ("reportEndTIme".equals(i.getName())) {
                    i.setName("reportEndTime");
                }
            });
            if (!CollectionUtils.isEmpty(defaultColumns)) {
                JSONArray jsonArray = (JSONArray) RedisUtil.get(vo.getType() + "_columns:" + LoginUtil.getLoginUserId());
                if (jsonArray != null && !jsonArray.isEmpty()) {
                    List<ColumnsConfigure> userColumns = jsonArray.toJavaList(ColumnsConfigure.class);

                    if (!CollectionUtils.isEmpty(userColumns)) {
                        List<ColumnsConfigure> existColumns = new ArrayList<>();
//                        List<ColumnsConfigure> otherColumns = new ArrayList<>();
                        List<ColumnsConfigure> finalDefaultColumns = defaultColumns;
                        userColumns.forEach(i -> {
                            ColumnsConfigure cc = finalDefaultColumns.stream().filter(f -> f.getName().equals(i.getName())).findAny().orElse(null);
                            if (Objects.nonNull(cc)) {
                                existColumns.add(i);
                            }
                        });
                        List<ColumnsConfigure> otherColumns = finalDefaultColumns.stream().filter(i -> !existColumns.stream().map(ColumnsConfigure::getName).collect(Collectors.toList()).contains(i.getName())).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(otherColumns)){
                            existColumns.addAll(otherColumns);
                        }
                        defaultColumns = existColumns;
                    }
                }
                RedisUtil.set(vo.getType() + "_columns:" + LoginUtil.getLoginUserId(), JSONArray.parseArray(JSON.toJSONString(defaultColumns)));
                //排除指定列(写死)
                if ("formInProduct".equals(vo.getType())) {
                    List<String> excludeNames = Arrays.asList("产品属性", "单位", "单位用量", "状态", "生产进度", "", "不良品数");
                    defaultColumns = defaultColumns.stream().filter(i -> !CollectionUtils.contains(excludeNames.iterator(), i.getChineseName())).collect(Collectors.toList());
                }

                return ResponseData.success(defaultColumns);
            }
        }
        return null;
    }

    @UserLoginToken
    @ApiOperation(value = "关联对象显示字段")
    @RequestMapping(value = "show_field", method = RequestMethod.POST)
    public ResponseData showField() {
        String str = OwnUtil.readFileTxt("showField.txt");
        List<ShowFieldResp> showFieldList = JSONArray.parseArray(str).toJavaList(ShowFieldResp.class);
        showFieldList.forEach(s -> {
            List<CustomField> customFieldList = customFieldService.list(new QueryWrapper<CustomField>().eq("field_ascription", s.getBusinessType()));
            if (!CollectionUtils.isEmpty(customFieldList)) {
                customFieldList.forEach(c -> {
                    ShowField sf = new ShowField();
                    sf.setChineseName(c.getChineseName());
                    sf.setName(c.getChineseName());
                    s.getDown().add(sf);
                });
            }
        });
        return ResponseData.success(showFieldList);
    }

    @UserLoginToken
    @ApiOperation(value = "关联属性中关联对象")
    @RequestMapping(value = "relation_object", method = RequestMethod.POST)
    public ResponseData relationObject(@RequestBody ColumnsHandle vo) {
        List<CustomField> customFieldList = customFieldService.list(new QueryWrapper<CustomField>().eq("field_type", "relevanceObject").eq(StringUtil.isNotBlank(vo.getType()), "field_ascription", vo.getType()));
        return ResponseData.success(customFieldList);
    }

    @UserLoginToken
    @ApiOperation(value = "关联对象-填充规则-字段信息")
    @RequestMapping(value = "fill_field_mess", method = RequestMethod.POST)
    public ResponseData fillFieldMess(@RequestBody FillFieldMessVo vo) {
        switch (vo.getType()) {
            case "product":
                Product product = productService.getById(vo.getId());
                if (StringUtil.isNotBlank(product.getOther())) {
                    product.setCustomFieldVos(customFieldService.handleCustomFieldForList(product.getOther()));
                }
                return ResponseData.success(product);
            case "processes":
                Processes processes = processesService.getById(vo.getId());
                if (StringUtil.isNotBlank(processes.getOther())) {
                    processes.setCustomFieldVos(customFieldService.handleCustomFieldForList(processes.getOther()));
                }
                return ResponseData.success(processes);
            case "user":
                User user = userService.getById(vo.getId());
                if (StringUtil.isNotBlank(user.getOther())) {
                    user.setCustomFieldVos(customFieldService.handleCustomFieldForList(user.getOther()));
                }
                return ResponseData.success(user);

        }
        return null;
    }

    @UserLoginToken
    @ApiOperation(value = "数据填充规则字段下拉")
    @RequestMapping(value = "fill_field", method = RequestMethod.POST)
    public ResponseData fillField(@RequestBody ColumnsHandle vo) {
        List<CustomField> customFieldList = customFieldService.list(new QueryWrapper<CustomField>()
                .eq("field_ascription", vo.getType())
                .ne("field_type", "relevanceObject")
                .ne("field_type", "relevanceProp"));
        return ResponseData.success(customFieldList);
    }


    @UserLoginToken
    @ApiOperation(value = "校验规则列表")
    @RequestMapping(value = "rule_list", method = RequestMethod.POST)
    public ResponseData ruleList(@RequestBody PageVo vo) {
        IPage<FormCheckRule> data = formCheckRuleService.page(new Page(vo.getPage(), vo.getLimit()));
        return ResponseData.success(data);
    }

    @UserLoginToken
    @ApiOperation(value = "校验规则编辑")
    @RequestMapping(value = "rule_edit", method = RequestMethod.POST)
    public ResponseData ruleEdit(@RequestBody FormCheckRule vo) {
        formCheckRuleService.saveOrUpdate(vo);
        return ResponseData.success("success");
    }

    @UserLoginToken
    @ApiOperation(value = "校验规则删除")
    @RequestMapping(value = "rule_del", method = RequestMethod.POST)
    public ResponseData ruleDel(@RequestBody IdVo vo) {
        formCheckRuleService.removeById(vo.getId());
        return ResponseData.success("success");
    }

    @UserLoginToken
    @ApiOperation(value = "自定义字段排序")
    @RequestMapping(value = "sort", method = RequestMethod.POST)
    public ResponseData sort(@RequestBody CustomFieldSort sort) {
        sort.getSort().forEach(s -> {
            CustomField cf = customFieldService.getById(s.getId());
            cf.setSort(s.getSort());
            customFieldService.updateById(cf);
        });
        return ResponseData.success("success");
    }

    @UserLoginToken
    @ApiOperation(value = "检查报工是否为固定字段或数字类型字段")
    @PostMapping(value = "checkFormula")
    public ResponseData<?> checkFormula(@RequestBody CheckFormula query) {
        if (!StringUtils.hasLength(query.getFormula())) {
            return ResponseData.success("成功!");
        }
        List<String> cuColumn = new ArrayList<>();

        if ("workReport".equals(query.getModule())) {
            query.setFormula(query.getFormula().replace("报工.", ""));
        }
        Matcher matcher = Pattern.compile("(?<=\\$\\{)(.+?)(?=})").matcher(query.getFormula());
        int i = 0;
        while (matcher.find()) {
            System.out.println(matcher.group(i));
            if ("workReport".equals(query.getModule()) && (!"良品数".equals(matcher.group(i)) && !"不良品数".equals(matcher.group(i)))) {
                cuColumn.add(matcher.group(i));
            }
            if (!"workReport".equals(query.getModule())) {
                cuColumn.add(matcher.group(i));
            }
            i++;
        }
        // 如果公式为自定义字段
        if (!cuColumn.isEmpty()) {
            List<CustomField> cuExist = customFieldService.list(new LambdaQueryWrapper<CustomField>().in(CustomField::getChineseName, cuColumn).eq(CustomField::getFieldType, "inputNumber"));
            Set<String> cuExistSet = cuExist.stream().map(CustomField::getChineseName).collect(Collectors.toSet());
            List<String> failColumn = new ArrayList<>();
            cuColumn.forEach(d -> {
                if (cuExistSet.add(d)) {
                    failColumn.add(d);
                }
            });
            if (cuExist.isEmpty() || !failColumn.isEmpty()) {
                return new ResponseData<>("字段不存在!", 500, failColumn.isEmpty() ? null : failColumn.get(0));
            }
        }
        return ResponseData.success("验证通过!");
    }

    /**
     * 单页中拖拽排序(仅限单页数据排序)
     *
     * @param param 排序后的数据列表
     */
    @UserLoginToken
    @PostMapping("pageColumnSort")
    public ResponseData<?> pageColumnSort(@RequestBody Map<String, List<CustomField>> param) {
        if (Objects.isNull(param)) {
            return ResponseData.fail(500, "参数不能为空!");
        }
        customFieldService.updateBatchById(param.get("customFields"));
        return ResponseData.success("修改成功!");
    }


}
